/*
 * @Description: 词云
 * @Author: YoungWind
 * @Date: 2020-09-28 17:10:43
 * @LastEditTime: 2020-09-29 22:06:06
 * @LastEditors: YoungWind
 * @FilePath: \ccd3\src\ccd3\wordCloud\charts\WordCloud.js
 */
import BaseChart from '../../BaseChart.js'
export default class WordCloud extends BaseChart {
  constructor(id, data) {
    super(id, data)
    this.words = null;
    this.padding = 0
    this.fontScale = 15
    this.fontFamily = "微软雅黑";
    this.backgroundColor = "white"
    this.color = d3.schemeCategory10;
    this.rotate = () => 0;
    this.spiral = size => {
      const e = size[0] / size[1];
      return function (t) {
        return [e * (t *= 0.01) * Math.cos(t), t * Math.sin(t)];
      };
    };
  }

  setFontScale(val = 15) {
    this.fontScale = val;
    return this;
  }

  setPadding(val = 0) {
    this.padding = val
    return this;
  }

  setBackgroundColor(val = "white"){
    this.backgroundColor = val
    return this;
  }


  setFontFamily(val = "微软雅黑") {
    this.fontFamily = val
    return this;
  }

  setColor(arr = d3.schemeCategory10) {
    this.color = arr;
    return this;
  }

  setRotate(callback) {
    this.rotate = callback;
    return this;
  }

  setSpiral(callback) {
    this.spiral = callback;
    return this;
  }


  init() {
    this.initSvg();
    this.initMainGroup();
    this.initCloud();
    return this;
  }

  initCloud() {
    this.cloudGroup = this.mg.append('g')
      .attr('transform', `translate(${this.innerWidth / 2},${this.innerHeight / 2})`)
      .attr("font-family", this.fontFamily)
      .style("color",this.backgroundColor)
      .attr("text-anchor", "middle");
  }

  render(data) {
    if (data) {
      this.data = data;
    }
    this.renderData();
    this.renderScale();
    this.renderCloudLayout();
    return this;
  }

  renderData() {
    this.words = d3.rollups(this.data, group => group.length, w => w)
      .sort(([, a], [, b]) => b - a)
      .slice(0, 250)
      .map(([text, value]) => ({ text, value }))
  }

  renderScale() {
    this.colorScale = d3.scaleOrdinal(this.color);
  }

  renderCloudLayout() {
    this.cloudLayout = d3.layout.cloud()
      .size([this.innerWidth, this.innerHeight])
      .words(this.words)
      .padding(this.padding)
      .rotate(this.rotate)
      .spiral(this.spiral)
      .font(this.fontFamily)
      .fontSize(d => Math.sqrt(d.value) * this.fontScale)
      .on("end", this.renderCloud);
    this.cloudLayout.start();
  }

  renderCloud = (words) => {
    this.cloudGroup
      .selectAll('text')
      .data(words)
      .join('text')
      .attr('fill', (d, i) => this.colorScale(i))
      .style("font-size", d => d.size)
      .attr("transform", d => `translate(${d.x},${d.y}) rotate(${d.rotate})`)
      .text(d => d.text)
  }
}